<template>
    <div>
        <van-nav-bar title="添加班级信息" left-text="返回" left-arrow @click-left="$router.go(-1)" />
        <van-form @submit="onSubmit">
            <van-field v-model="newClazzName" name="newClazzName" label="班级名称" placeholder="请输入班级名称"
                :rules="[{ required: true, message: '请填写班级名称' }]">
                <template #button>
                    <van-button size="small" type="primary" @click="addClazz">添加</van-button>
                </template>
            </van-field>
            <van-cell-group>
                <van-cell v-for="(name, index) in clazzNames" :key="index" :title="name">
                    <template #right-icon>
                        <van-icon name="cross" @click="removeClazz(index)" />
                    </template>
                </van-cell>
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button @click="onSubmit" round block type="primary" native-type="submit">
                    提交
                </van-button>
            </div>
        </van-form>
    </div>
</template>

<script>
import { Toast } from 'vant';
import service from '@/api';

export default {
    data() {
        return {
            newClazzName: '',
            clazzNames: []
        };
    },
    methods: {
        addClazz() {
            if (this.newClazzName.trim()) {
                this.clazzNames.push(this.newClazzName.trim());
                this.newClazzName = '';
            }
        },
        removeClazz(index) {
            this.clazzNames.splice(index, 1);
        },
        async onSubmit() {
            if (this.clazzNames.length === 0) {
                Toast.fail('请至少添加一个班级名称');
                return;
            }
            await service.post('/api/clazz', this.clazzNames, "添加班级信息");
            Toast.success('添加成功');
            setTimeout(() => {
                this.$router.go(-1); // 返回上一页
            }, 1000);
        }
    }
};
</script>

<style scoped>
.van-form {
    margin-top: 20px;
}
</style>